package com.cn.tianxin.ssserver.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpUtil {

    public static final String CODE = "UTF-8";

    //将map参数，转换为url-encode的字符串
    public static String map2UrlParam(Map<String, Object> paramMap, boolean sort) {
        if (paramMap == null || paramMap.size() == 0) return "";

        Set<String> keySet = paramMap.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        if (sort) {
            Arrays.sort(keyArray);
        }

        StringBuilder sb = new StringBuilder();
        try {
            for (int i = 0; i < keyArray.length; i++) {
                if (i == (keyArray.length - 1)) {
                    sb.append(String.format("%s=%s", keyArray[i], URLEncoder.encode(paramMap.get(keyArray[i]).toString(), CODE)));
                } else {
                    sb.append(String.format("%s=%s&", keyArray[i], URLEncoder.encode(paramMap.get(keyArray[i]).toString(), CODE)));
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static byte[] httpRequest(String urlStr, Map<String, Object> args) throws IOException {
        return httpRequest(urlStr,args,"GET");
    }

    public static void main(String[] args) throws IOException {
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("js_code","code235nn13kk134");
        reqMap.put("appid","666666");
        reqMap.put("secret","555555&%feae55");
        reqMap.put("grant_type","authorization_code");
        String str = map2UrlParam(reqMap, true);
        System.out.println("str=>"+str);
        byte[] bytes = HttpUtil.httpRequest("https://api.weixin.qq.com/sns/jscode2session", reqMap);
        String resStr = new String(bytes,CODE);

        System.out.println("resStr=>"+resStr);

    }

    public static byte[] httpRequest(String urlStr, Map<String, Object> args, String method) throws IOException {
        return httpRequest(urlStr,map2UrlParam(args,true),method);
    }

    public static byte[] httpRequest(String urlStr, String reqStr, String method) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        method = (method!=null && "POST".equals(method.trim().toUpperCase()))?"POST":"GET";
        urlConnection.setRequestMethod(method);

        //添加参数
        urlConnection.setConnectTimeout(10*1000);
        urlConnection.setReadTimeout(10*1000);
        urlConnection.setDoOutput(true);//允许带参数
        urlConnection.setDoInput(true);//允许带参数
        OutputStream outputStream = urlConnection.getOutputStream();
        if (reqStr!=null && !"".equals(reqStr.trim())){
            outputStream.write(reqStr.getBytes(CODE));
        }

        System.out.println("HttpUtil.httpRequest=>content============>"+urlStr+"    reqStr=>"+reqStr);

        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        int available = inputStream.available();
        byte[] bytes = new byte[available];
        inputStream.read(bytes);

        System.out.println("HttpUtil.httpRequest=>result=============>"+new String(bytes,CODE));

        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytes;
    }

    // 处理点字节内容
    // 再次提交一条内容到 newIdea分支
    // 再来盖一条
    public static byte[] httpPostJSON(String url, String jsonStr) throws IOException {
        return httpRequest(url,jsonStr,"POST");
    }

}
